package com.ysu.concurrency.thread.future;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author 郭辉
 * @className TestFuture
 * @description java 异步回调
 * @date 2021/12/27 10:16
 * @company 海康威视
 */
public class TestFuture{
    public static void main(String[] args) {
//        test1();
        test2();
    }

    //异步执行---- 无返回值的调用方法
    private static void test1() {
        //异步执行---- 无返回值的调用方法
        Future<Void> future = CompletableFuture.runAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"runAsync ==> Void");
        });

        System.out.println("测试异步执行");

        try {
            //阻塞回调
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    private static void test2() {
        //异步执行---- 无返回值的调用方法
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(()->{
            System.out.println(Thread.currentThread().getName()+"runAsync ==> Integer");
            int a = 1/0;
            return 200;
        });

        System.out.println("测试异步执行");

        future.whenComplete((t,u)->{ //正常的返回结果
            System.out.println(t); // 正常的返回结果
            System.out.println(u); // 错误信息
        }).exceptionally((e)->{
            e.printStackTrace(); //可以获取到错误的返回结果
            return 500;
        });
    }
}
